﻿using Microsoft.EntityFrameworkCore;
using Project.IRepository;
using Project.IService;
using Project.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project.Service
{
    public class UserBegoodatService:IUserBegoodatService
    {
        private readonly ProjectDbContext dbContext;
        private readonly IUnitOfWork unitOfWork;

        public UserBegoodatService(ProjectDbContext dbContext,IUnitOfWork unitOfWork)
        {
            this.dbContext = dbContext;
            this.unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 根据雇员id获取擅长项目
        /// </summary>
        /// <param name="empId"></param>
        /// <returns></returns>
        public IQueryable<BeGoodAt> GetBegoodAts(Guid empId)
        {
           return  dbContext.UserBegoodatRelation.Where(b => b.UserId == empId).Include(n=>n.BeGoodAt)
                .Select(n => n.BeGoodAt).Where(n=>n.IsDeleted==false);
        }

        public async Task<int> SetBegoodatAsync(Guid empId,List<Guid> begoodatIds)
        {
            var existsBids = await GetBegoodAts(empId).Select(n => n.Id).ToListAsync(); // 现存在的擅长对象id
            var deleteingBids = existsBids.Except(begoodatIds); // 要删除的项
            var addingBids = begoodatIds.Except(existsBids);  // 要新增的项

            // 移除
            foreach(var bid in deleteingBids)
            {
                dbContext.UserBegoodatRelation.Remove(new UserBegoodatRelation() { UserId = empId, BeGoodAtId = bid });
            }

            // 增加
            foreach(var bid in addingBids)
            {
                dbContext.UserBegoodatRelation.Add(new UserBegoodatRelation() { UserId = empId, BeGoodAtId = bid });
            }

            return await unitOfWork.SaveChangesAsync();
        }

        


    }
}
